<?php
/**
 * Created by PhpStorm.
 * User: mr_lee
 * Date: 2017/10/17
 * Time: 上午10:45
 */

namespace app\index\controller;


use Alipay\Alipayobj;
use app\common\controller\Deviceobj;
use app\common\model\Agent;
use app\common\model\Merchant;
use app\common\model\Paylog;
use app\common\model\System;
use app\common\model\WxOpen;
use app\common\model\WxUser;
use think\Controller;
use think\Session;
use Wechat\Wxobjopen;

class Cmmbpay extends Controller
{
    private $uid;
    public function pay()
    {
        $request = request();
        Session::set('openid', null);
        $map['id'] = $request->param('id');

        $Merchant = new Merchant();
        $Agent = new Agent();
        $System = new System();
        $WxOpen = new WxOpen();
        $user = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $user['agent']))->find();
        $config = $System->where(array('id' => 1))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );

        $weObj = new Wxobjopen($options);
        $openid = session('openid');
        if (strlen($openid) <= 10) {
            $info = $weObj->getOpenoauthAccessToken();
            if (!$info) {
                $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("Cmmbpay/pay", array('id' => $request->param('id')));
                $url = $weObj->getopenOauthRedirect($callback, '', 'snsapi_base');

                header("Location: $url");
                exit();
            } else {

                $openid = $info['openid'];

                session('openid', $openid);
            }
        }
        //jssdk
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $jssdk = $weObj->getJsSign($url);
        $this->assign('jssdk', $jssdk);
        $this->get_user_info($openid, $request->get('id'));
        $this->assign("headimg", $user['img']);
        $this->assign('shmc', $user['merchant']);
        $this->assign('id', $request->param('id'));
        $this->assign('openid', $openid);
        return $this->fetch("cmmbpay/pay");

    }


    public function pay2()
    {
        $request = request()->param();
        $Paylog = new Paylog();
        $norderid = $Paylog->where(array('orderid' => request()->post('orderid')))->count();
        if ($norderid != 0) {
            $param=array('code'=>2,'message'=>'网络错误');

        } else {
            $Merchant = new Merchant();
            $System = new System();
            $WxOpen = new WxOpen();
            $Agent= new Agent();
            $map['id'] = $request['id'];
            $config = $Merchant->where($map)->find();
            $sysconfig = $System->where(array('id' => 1))->find();
            $users = $WxOpen->where(array('id' => $sysconfig['wx_open_id']))->find();
            $agent=$Agent->where(array('id'=>$config['agent']))->find();
            $options = array(
                'component_token' => $sysconfig['component_token'], // 填写你设定的key
                'component_encodingaeskey' => $sysconfig['component_encodingaeskey'], // 填写加密用的EncodingAESKey
                'component_appid' => $sysconfig['component_appid'], // 填写高级调用功能的app id
                'component_appsecret' => $sysconfig['component_appsecret'], // 填写高级调用功能的密钥
                'open_ticket' => $sysconfig['open_ticket'],
                'authorizer_appid' => $users['authorizer_appid'],
                'authorizer_refresh_token' => $users['authorizer_refresh_token'],
                'cmmb_key' => $agent['cmmb_key'],
            );
            $weObj = new Wxobjopen($options);
            $price = request()->post('price');
            $appid = $users['authorizer_appid'];
            $mch_id = $agent['cmmb_mch_id'];
            $out_trade_no = request()->post('orderid');
            $body = "快捷支付";
            $sub_mch_id = $config['cmmb_mer_id'];
            $total_fee = $price * 100;
            $data['orderid'] = $out_trade_no;
            $data['mid'] = request()->param('id');
            $data['openid'] = request()->post('openid');
            $data['pay_statu'] = 0;
            $data['price'] = $price;
            $data['add_time'] = time();
            $Paylog = new Paylog();
            $add = $Paylog->save($data);
            $notify_url = 'http://mstz.weilinzhou.com/ms_api.php';
            $param['merNo'] = $sub_mch_id;
            $param['orderNo'] = $out_trade_no;
            $param['amount'] = $total_fee;
            $param['reqId'] = $out_trade_no;
            $param['subAppId'] = $appid;
            $param['reqTime'] = date('YmdHis');
            $param['subOpenId'] = request()->post('openid');
            $param['notifyUrl'] = $notify_url;
            $param['goodsName'] = $body;
            $param['bigMerNo'] = $mch_id;
            $param['isShowSelfName'] = 1;
            $param['signIn'] = $weObj->getcmmbpaysignature($param);
            $sj = $weObj->getcmmbpay($param);
            $sj = json_decode($sj, true);
            if (isset($sj['appId'])) {
                if ($sj['appId'] == '') {

                    $param=array('code'=>2,'message'=>'民生银行接口错误');

                }else{
                    $jsApiObj["appId"] = $sj['appId'];
                    $jsApiObj["timeStamp"] = $sj['timeStamp'];
                    $jsApiObj["nonceStr"] = $sj['nonceStr'];
                    $jsApiObj["package"] = $sj['pack'];
                    $jsApiObj["signType"] = $sj['signType'];
                    $jsApiObj["paySign"] = $sj['paySign'];

                    $param = $jsApiObj;
                }
            } else {
                $param=array('code'=>2,'message'=>'民生银行接口错误');

            }
            return json($param);
        }

    }


    public function ms_orderquery($orderid)
    {
        $Paylog = new Paylog();
        $mab['orderid'] = $orderid;
        $id = $Paylog->where($mab)->find();
        $map['id'] = $id['mid'];
        $Merchant = new Merchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $config = $Merchant->where($map)->find();
        $Agent= new Agent();
        $agent=$Agent->where(array('id'=>$config['agent']))->find();
        $sysconfig = $System->where(array('id' => 1))->find();
        $users = $WxOpen->where(array('id' => $sysconfig['wx_open_id']))->find();

        $options = array(
            'component_token' => $sysconfig['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $sysconfig['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $sysconfig['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $sysconfig['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $sysconfig['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
            'cmmb_key' => $agent['cmmb_key'],
        );
        $weObj = new Wxobjopen($options);
        $param['merNo'] = $config['cmmb_mer_id'];
        $param['orderNo'] = $orderid;
        $param['signIn'] = $weObj->getcmmbpaysignature($param);
        $sj = $weObj->getcmmborderquery($param);
        $sj = json_decode($sj, true);
        $pay_zt = $sj['result'];


        if ($pay_zt == 0000) {

            $data['orderno'] = $sj['outOrderNo'];
            $data['pay_time'] = $sj['payTime'];
            $data['payinfo'] = json_encode($sj);
            $data['pay_statu'] = 1;

            $up = $Paylog->save($data, ['orderid'=> $orderid]);
            ;
            if ($id['tzzt'] == '0') {
                $s = action('Wxauth/sendtemplate', array($id['mid'], $orderid));
                action('Index/sendprint', array($id));
                $Deviceobj = new Deviceobj();
                $s=$Deviceobj->ylb_sendvoice($orderid);
                $da['tzzt'] = 1;
                $da['tzmsg'] = json_encode($s);
                $Paylog->save($da, ['orderid' => $orderid]);

            }
        }


    }

    public function payover()
    {
        $request = request();
        $map['id'] = $request->param('id');
        $Merchant = new Merchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent=new Agent();

        $config = $Merchant->where($map)->find();
        $agent=$Agent->where(['id'=>$config['agent']])->find();
        $sysconfig = $System->where(array('id' => 1))->find();
        $users = $WxOpen->where(array('id' => $sysconfig['wx_open_id']))->find();

        $options = array(
            'component_token' => $sysconfig['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $sysconfig['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $sysconfig['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $sysconfig['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $sysconfig['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
            'cmmb_key' => $agent['cmmb_key'],
        );
        $weObj = new Wxobjopen($options);
        $param['merNo'] = $config['cmmb_mer_id'];
        $param['orderNo'] = $request->param('orderid');
        $param['signIn'] = $weObj->getcmmbpaysignature($param);
        $sj = $weObj->getcmmborderquery($param);
        $sj = json_decode($sj, true);
        $this->ms_orderquery($sj['orderNo']);
        $pay_zt = $sj['result'];


        if ($pay_zt == 0000) {


            $data = 0;
        } else {
            $data = 1;
        }
        return json($data);
//
//        if ($pay_zt == "SUCCESS") {
//            $data = 0;
//        } else {
//            $data = 1;
//        }
//        echo $data;
    }


    public function orderinfo()
    {
        $request = request();
        $map['id'] = $request->param('id');
        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $System=new System();
        $Sysconfig=$System->where('id',1)->find();
        $config = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
        $options = array(
            'component_token' => $Sysconfig['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $Sysconfig['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $Sysconfig['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $Sysconfig['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $Sysconfig['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        $weObj = new Wxobjopen($options);
        $openid = session('openid');
        if (strlen($openid) <= 10) {
            $info = $weObj->getOpenoauthAccessToken();
            if (!$info) {
                $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("cmmnpay/orderinfo", array('id' => $request->param('id')));
                $url = $weObj->getopenOauthRedirect($callback, '', 'snsapi_base');

                header("Location: $url");
                exit();
            } else {

                $openid = $info['openid'];

            }
        }
        $Paylog = new Paylog();

        $maq['orderid'] = $request->param('orderid');
        $order = $Paylog->where($maq)->find();
        if ($openid == $order['openid']) {
            $mav['id'] = $request->param('id');
            $shmc = $Merchant->where($mav)->value('merchant');


            $this->assign('shmc', $shmc);
            $this->assign('order', $order);
            $this->assign('id', $request->param('id'));
            $this->assign('orderid', $request->param('orderid'));
        } else {
            $this->error('非订单支付者无法查看订单详情');
        }
        //jssdk
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $jssdk = $weObj->getJsSign($url);
        $this->assign('jssdk', $jssdk);
        $this->assign('jssdk', $jssdk);
        return $this->fetch('index/orderinfo');
    }

    public function alipayorderinfo()
    {
        $Merchant = new Merchant();
        $Agent = new Agent();
        $request = request();
        $users = $Merchant->where(array('id' => $request->param('id')))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $raskey = $agent['ali_app_key'];
        $options = array(
            //'token' => $config ["token"], // 填写你设定的key
            //'encodingaeskey' => $config ["encodingaeskey"], // 填写加密用的EncodingAESKey
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],

        );
        $aliObj = new Alipayobj($options);

        if ($request->get('auth_code')||$request->param('auth_code')) {
            $param['app_id'] = $agent['ali_app_id'];
            $param['method'] = "alipay.system.oauth.token";
            $param['charset'] = "UTF-8";
            $param['sign_type'] = "RSA";
            $param['version'] = '1.0';
            $param['timestamp'] = date('Y-m-d H:i:s');
            $param['grant_type'] = 'authorization_code';
            $param['code'] = $request->param('auth_code');
            $signContent = $aliObj->rsaSign($param, $signType = "RSA");

            //$sign2 = $aliObj->alonersaSign($signContent, $raskey, $signType = "RSA", $keyfromfile = false);

            // var_dump($sign);
            $param['sign'] = $signContent;
            $uid = $aliObj->getuid($param);
            $user = json_decode($uid, true);
            $this->uid = $user['alipay_system_oauth_token_response']['user_id'];

        } else {

            $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("Cmmbpay/alipayorderinfo", array('id' => $request->param('id'), 'orderid' => $request->param('orderid')));
            $url = $aliObj->getOauthRedirect($callback, '', 'auth_userinfo');
            header("Location: $url");
        }
        $maq['orderid'] = $request->param('orderid');
        $Paylog = new Paylog();
        $order = $Paylog->where($maq)->find();

        if ($this->uid == $order['openid']) {

            $mav['id'] = $request->param('id');
            $shmc = $Merchant->where($mav)->value('merchant');


            $this->assign('shmc', $shmc);
            $this->assign('order', $order);
            $this->assign('id', $request->param('id'));
            $this->assign('orderid', $request->param('orderid'));
            return $this->fetch("alipay/orderinfo");
        } else {
            $this->error('非订单支付者无法查看订单详情');
        }

    }

    public function get_user_info($openid = 'ok2ajuAJm7owX6UaYGoQZ05YFcww', $id = 1)
    {
        $us['openid'] = $openid;
        $WxUser = new WxUser();
        $user = $WxUser->where("openid='$openid'")->count();
        if ($user == 0) {
            $map['id'] = $id;
            $Merchant = new Merchant();
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $System = new System();
            $user = $Merchant->where($map)->find();
            $agent = $Agent->where(array('id' => $user['agent']))->find();
            $config = $System->where(array('id' => 1))->find();
            $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
            $options = array(
                'component_token' => $config['component_token'], // 填写你设定的key
                'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
                'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
                'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
                'open_ticket' => $config['open_ticket'],
                'authorizer_appid' => $users['authorizer_appid'],
                'authorizer_refresh_token' => $users['authorizer_refresh_token'],
            );
            $weObj = new Wxobjopen ($options);
            $userinfo = $weObj->getUserInfo($openid);
            $userinfo = json_encode($userinfo);


            $data['openid'] = $openid;
            $data['wx_info'] = $userinfo;
            $data['addtime'] = time();
            $WxUser = new WxUser();
            $add = $WxUser->save($data);

        }
    }

    public function getorder2()
    {
        $request = request();
        if ($request->isAjax()) {
            $sh = $request->post('id');
            $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999);
            echo $order;
        }
    }

    public function getorder($sh)
    {

        $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999);
        return $order;
    }


    public function alipay()
    {
        $Merchant = new Merchant();
        $Agent = new Agent();
        $request = request();
        $users = $Merchant->where(array('id' => $request->param('id')))->find();
//        if ($users['ali_merid'] == '') {
//            $this->error('当前商户未开启支付宝支付功能');
//        }
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $raskey = $agent['ali_app_key'];
        $options = array(
            //'token' => $config ["token"], // 填写你设定的key
            //'encodingaeskey' => $config ["encodingaeskey"], // 填写加密用的EncodingAESKey
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],

        );
        $aliObj = new Alipayobj($options);
        if ($request->get('auth_code')) {
            $param['app_id'] = $agent['ali_app_id'];
            $param['method'] = "alipay.system.oauth.token";
            $param['charset'] = "UTF-8";
            $param['sign_type'] = "RSA";
            $param['version'] = '1.0';
            $param['timestamp'] = date('Y-m-d H:i:s');
            $param['grant_type'] = 'authorization_code';
            $param['code'] = $request->get('auth_code');
            $signContent = $aliObj->rsaSign($param, $signType = "RSA");

            //$sign2 = $aliObj->alonersaSign($signContent, $raskey, $signType = "RSA", $keyfromfile = false);

            // var_dump($sign);
            $param['sign'] = $signContent;
            $uid = $aliObj->getuid($param);
            $user = json_decode($uid, true);
            $uid = $user['alipay_system_oauth_token_response']['user_id'];
            $this->assign("headimg", $users['img']);
            $this->assign('shmc', $users['merchant']);
            $this->assign('id', $request->param('id'));
            $this->assign('uid', $uid);
            return $this->fetch();

        } else {
            $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("cmmbpay/alipay", array('id' => $request->param('id')));
            $url = $aliObj->getOauthRedirect($callback, '', 'auth_base');
//        echo $url;
//        exit();
            header("Location: $url");
        }


    }

    public function alipaypay()
    {
        $request = request();
        $Paylog = new Paylog();
        $norderid = $Paylog->where(array('orderid' => request()->post('orderid')))->count();
        if ($norderid != 0) {
            echo 1;

        } else {
            $Merchant = new Merchant();
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $users = $Merchant->where(array('id' => $request->param('id')))->find();
            $agent = $Agent->where(array('id' => $users['agent']))->find();
            $raskey = $agent['ali_app_key'];
            $cmmb_key = $WxOpen->where(array('id' => $agent['wx_open_id']))->value('cmmb_key');
            $options = array(
                //'token' => $config ["token"], // 填写你设定的key
                //'encodingaeskey' => $config ["encodingaeskey"], // 填写加密用的EncodingAESKey
                'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                'rsaPrivateKey' => $agent['ali_app_key'],
                'cmmb_key' => $cmmb_key,
            );
            $aliObj = new Alipayobj($options);

            $price = request()->post('price');
            $buyer_id = request()->post('buyer_id');
            $out_trade_no = request()->post('orderid');
            $body = "快捷支付";
            $total_fee = $price * 100;
            $notify_url = 'http://mstz.weilinzhou.com/ms_api.php';
            $param['notifyUrl'] = $notify_url;
            $param['merNo'] = $users['cmmb_mer_id'];;
            $param['goodsName'] = $body;
            $param['orderNo'] = $out_trade_no;
            $param['channelFlag'] = "01";
            $param['amount'] = $total_fee;
            $param['reqId'] = $out_trade_no;
            $param['reqTime'] = date('YmdHis');
            $param['alipayUserId'] = request()->post('buyer_id');
            $param['signIn'] = $aliObj->getcmmbpaysignature($param);
            $order = json_decode($aliObj->getcmmbpay($param), true);
            $orderid = $order['tradeNo'];


            $sdata['orderid'] = $out_trade_no;
            $sdata['mid'] = $request->param('id');
            $sdata['openid'] = request()->post('buyer_id');
            $sdata['pay_statu'] = 0;
            $sdata['price'] = $price;
            $sdata['add_time'] = time();
            $sdata['pay_fs'] = 1;

            $add = $Paylog->save($sdata);

            return json($orderid);
        }
    }

    public function test()
    {

        $s = $this->ms_orderquery("H724-2017092218391351897");
        var_dump($s);

    }

}